package com.clstu.event;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class BallMove extends JFrame {

    MyPanel mp = null;

    public BallMove(){
        mp = new MyPanel();//
        this.add(mp);
        this.addKeyListener(mp);//把键盘监听器加入到窗口中去
        this.setSize(500,400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }

    public static void main(String[] args) {
       new BallMove();
    }

}
class MyPanel extends JPanel implements KeyListener {//KeyListener 是用来监听键盘输入的

    int x=10;
    int y=10;

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.fillOval(x,y,10,10);

    }

    @Override//有字符输出时，该方法触发
    public void keyTyped(KeyEvent e) {

    }

    @Override//某个键被按下，该方法触发
    public void keyPressed(KeyEvent e) {

        System.out.println((char)e.getKeyCode()+"键被按下~~~");
        if(e.getKeyCode()==KeyEvent.VK_DOWN){
            y++;
        }
        else if(e.getKeyCode()==KeyEvent.VK_UP) y--;
        else if(e.getKeyCode()==KeyEvent.VK_LEFT) x--;
        else if(e.getKeyCode()==KeyEvent.VK_RIGHT) x++;
        
        repaint();//重绘方法在这里调用，因为会持续监听，听一次就调用一次，实时变化。

    }

    @Override//当某个键抬起，该方法触发
    public void keyReleased(KeyEvent e) {

    }
}